package com.ziyia.viewmodel;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class ViewModelTest extends AppCompatActivity {
    private static MainViewModel mainViewModel = null;
    private static SharedPreferences sharedPreferences = null;
    private TextView infoText = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_model_test);


        // 设置标题
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setTitle("ViewModel - Test");
        }

        // 获取infoText
        infoText = findViewById(R.id.infoText);

        sharedPreferences = getPreferences(Context.MODE_PRIVATE);
        int count_reserved = sharedPreferences.getInt("count_reserved", 0);

        // 通过ViewModelProvider 获取 MainViewModel
//        mainViewModel = new ViewModelProvider(ViewModelTest.this).get(MainViewModel.class);

        //
        mainViewModel = new ViewModelProvider(ViewModelTest.this, new MainViewModelFactory(count_reserved)).get(MainViewModel.class);


        // 观察数据的变化
        mainViewModel.getLiveData().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                Log.d(MainActivity.class.getName(), "onChanged: 数据有变化，嘿嘿");
                infoText.setText(integer.toString());
            }
        });

        // map方式观察数据的变化
        mainViewModel.getUserName().observe(this, e -> {
            Log.d("userlog", e.toString());
        });
        mainViewModel.setUser(new User("年少有为", 18));


        mainViewModel.getSwitchUserLiveData().observe(this, new Observer<User>() {
            @Override
            public void onChanged(User user) {
                Log.d("switchUserLiveData", "周五的夜晚");
            }
        });
        mainViewModel.switchTest("emmmmmm");
    }

    // 数值  + 1
    public void jji(View view) {
        mainViewModel.plusOne();
    }


    // 请零
    public void clear(View view) {
        mainViewModel.clear();
    }


    // Activity销毁时保存数据
    @Override
    protected void onPause() {
        super.onPause();
        sharedPreferences.edit().putInt("count_reserved", mainViewModel.getLiveData().getValue());
    }
}